package com.ruoyi.invoice.service.impl;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.exception.CustomException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.invoice.domain.*;
import com.ruoyi.invoice.dto.SalesInvoiceDTO;
import com.ruoyi.invoice.dto.SalesInvoiceProductsDTO;
import com.ruoyi.invoice.mapper.*;
import com.ruoyi.invoice.vo.SalesInvoiceDetailVo;
import com.ruoyi.invoice.vo.SalesInvoiceVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.invoice.service.ISalesInvoiceService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 销项发票Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-03-06
 */
@Service
@Slf4j
public class SalesInvoiceServiceImpl implements ISalesInvoiceService 
{
    @Autowired
    private SalesInvoiceMapper salesInvoiceMapper;

    // 发票种类
    @Autowired
    private SalesInvoiceTypeMapper salesInvoiceTypeMapper;

    // 业务类型
    @Autowired
    private BusinessTypeMapper businessTypeMapper;

    //  模版
    @Autowired
    private InvoiceTemplateMapper invoiceTemplateMapper;

    //  商品
    @Autowired
    private InvoiceProductsMapper invoiceProductsMapper;

    // 客户信息
    @Autowired
    private CustomerInfoMapper customerInfoMapper;

    /**
     * 查询销项发票
     * 
     * @param salesInvoiceId 销项发票主键
     * @return 销项发票 TODO
     */
    @Override
    public SalesInvoiceDetailVo selectSalesInvoiceBySalesInvoiceId(Long salesInvoiceId)
    {

        return salesInvoiceMapper.selectSalesInvoiceBySalesInvoiceId(salesInvoiceId);
    }

    /**
     * 查询销项发票列表
     * 
     * @param
     * @return 销项发票
     */
    @Override
    public List<SalesInvoiceVO> selectSalesInvoiceList(SalesInvoiceDTO salesInvoiceDTO)
    {
        return salesInvoiceMapper.selectSalesInvoiceList(salesInvoiceDTO);
    }

    /**
     * 新增销项发票
     * 
     * @param
     * @return 结果
     */
    @Override
    @Transactional
    public int insertSalesInvoice(SalesInvoiceProductsDTO salesInvoiceProductsDTO)
    {
        SalesInvoice salesInvoice = new SalesInvoice();
        BeanUtils.copyBeanProp(salesInvoice,salesInvoiceProductsDTO);

        // 赋值客户实体
        CustomerInfo customerInfo = new CustomerInfo();
        BeanUtils.copyBeanProp(customerInfo,salesInvoiceProductsDTO);

        // 如果客户id为空，不让添加
        if (customerInfo.getCustomerId() == null) {
            throw new CustomException("系统异常：新增数据，id获取失败");
        }
        // 修改客户信息
        int i2 = customerInfoMapper.updateById(customerInfo);


        // 校验发票号码的唯一性
        LambdaQueryWrapper<SalesInvoice> eq = new QueryWrapper<SalesInvoice>().lambda().eq(SalesInvoice::getInvoiceNumber, salesInvoice.getInvoiceNumber());
        List<SalesInvoice> salesInvoices = salesInvoiceMapper.selectList(eq);
        if (salesInvoices.size() > 0) {
            throw new CustomException("发票号码重复");
        }

        // 添加销项发票数据
        int i = salesInvoiceMapper.insertSalesInvoice(salesInvoice);
        if (i == 0) {
            throw new CustomException("系统异常：新增数据失败");
        }

        // 获取开票商品数据，关联使用
        List<InvoiceProducts> details = salesInvoiceProductsDTO.getDetails();

        // 定义hashset对开票商品去重操作
        HashSet<Long> set = new HashSet<>();
        for (InvoiceProducts detail : details) {
            set.add(detail.getId());
            detail.setSalesInvoiceId(salesInvoice.getSalesInvoiceId());
            int i1 = invoiceProductsMapper.updateById(detail);
            if (i1 == 0) {
                throw new CustomException("系统异常：新增数据失败");
            }
        }

        // 校验发票商品是否重复
        if (set.size() != details.size()) {
            throw new CustomException("商品不能重复");
        }
        return 1;
    }

    /**
     * 修改销项发票
     * 
     * @param salesInvoice 销项发票
     * @return 结果
     */
    @Override
    public int updateSalesInvoice(SalesInvoice salesInvoice)
    {
        salesInvoice.setUpdateTime(DateUtils.getNowDate());
        return salesInvoiceMapper.updateSalesInvoice(salesInvoice);
    }

    /**
     * 批量删除销项发票
     * 
     * @param salesInvoiceIds 需要删除的销项发票主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteSalesInvoiceBySalesInvoiceIds(Long[] salesInvoiceIds)
    {
        for (Long salesInvoiceId : salesInvoiceIds) {
            QueryWrapper<InvoiceProducts> invoiceProductsQueryWrapper = new QueryWrapper<>();
            invoiceProductsQueryWrapper.lambda().eq(InvoiceProducts::getSalesInvoiceId, salesInvoiceId);
            List<InvoiceProducts> invoiceProducts = invoiceProductsMapper.selectList(invoiceProductsQueryWrapper);
            for (InvoiceProducts invoiceProduct : invoiceProducts) {
                invoiceProduct.setSalesInvoiceId(0L);
                invoiceProductsMapper.updateById(invoiceProduct);
            }
        }
        return salesInvoiceMapper.deleteSalesInvoiceBySalesInvoiceIds(salesInvoiceIds);
    }

    /**
     * 删除销项发票信息
     * 
     * @param salesInvoiceId 销项发票主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteSalesInvoiceBySalesInvoiceId(Long salesInvoiceId)
    {
        QueryWrapper<InvoiceProducts> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(InvoiceProducts::getSalesInvoiceId, salesInvoiceId);
        List<InvoiceProducts> invoiceProducts = invoiceProductsMapper.selectList(queryWrapper);
        for (InvoiceProducts invoiceProduct : invoiceProducts) {
            invoiceProduct.setSalesInvoiceId(null);
            invoiceProductsMapper.updateById(invoiceProduct);
        }

        return salesInvoiceMapper.deleteSalesInvoiceBySalesInvoiceId(salesInvoiceId);
    }

    /**
     * 查询下拉框数据
     * @return
     */
    @Override
    public Map<String, List<?>> getSelectAllData() {
        // 查询发票种类下拉框数据
        List<SalesInvoiceType> salesInvoiceTypes = salesInvoiceTypeMapper.selectList(null);

        // 查询业务类型下拉框数据
        List<InvoiceBusinessType> invoiceBusinessTypes = businessTypeMapper.selectList(null);

        // 查询模版下拉框数据
        List<InvoiceTemplate> invoiceTemplates = invoiceTemplateMapper.selectList(null);

        // 商品下拉框数据
        QueryWrapper<InvoiceProducts> qw = new QueryWrapper<>();
        qw.lambda().eq(InvoiceProducts::getSalesInvoiceId, 0);
        List<InvoiceProducts> invoiceProducts = invoiceProductsMapper.selectList(qw);
        List<CustomerInfo> customerInfos = customerInfoMapper.selectList(null);


        HashMap<String, List<?>> map = new HashMap<>();
        map.put("salesInvoiceList", salesInvoiceTypes);
        map.put("businessTypeList", invoiceBusinessTypes);
        map.put("invoiceTemplates", invoiceTemplates);
        map.put("invoiceProducts", invoiceProducts);
        map.put("customerInfos", customerInfos);
        return map;
    }
}
